import React from "react";
import {Button,  Divider,  Menu, Modal} from 'antd/lib';
import ContractTable from "@/components/contract/new/ContractTable";
import Enums from "@/services/enums";
import notification from "@/services/notification";
import {get} from "lodash";
import {currentUser} from "@/services/auth";
import Workflow from "@/services/workflow";
import Execute from "@/components/contract/new/Execute";
import EditorDemo from "@/components/contract/new/EditorDemo";
import Template from "@/components/contract/new/Template";
import AttacheTab from "@/components/contract/new/AttacheTab";
import moment from "moment";
import Attaches from "@/services/attaches";
import Customer from "@/services/customer";
import GlobalSetting from "@/services/globalsetting";
import WarningOutlined from "@ant-design/icons/WarningOutlined";
import {createBrowserHistory} from 'history';
import Workflow_state from "@/services/workflow_state";
import { inject, observer } from 'mobx-react';
import GlobalFunctions from '@/store/globalFunctions';
const customHistory = createBrowserHistory();
const { confirm } = Modal;

class Toolbar extends React.Component {
  state = {
    loading: true,
    openpage:"jbxx",
    volumepurchaseunit:"",
    kuangjiaxieyi: "",
    beianhetong:"",
    contracttypedata:[],
    departmentdata:[],//HRP部门表
    employeedata:[],
    yusuandata:[],
    budgetset:[],
    amounttypedata:[],
    contracttypenewdata:[],
    customerdata:[],
    purchaseemployeedata:[],
    tablefielddata:[{code:'code',name:"预编码"}],
  };
  componentWillMount() {
    Enums.items("contract_enum").then(data => {
      this.setState({
        contracttypedata: data,
        loading: false,
      });
    });
    Enums.items("amounttype").then(data => {
      this.setState({
        amounttypedata: data,
      });
    });
    Enums.items("contracttype").then(data => {
      this.setState({
        contracttypenewdata: data,
      });
    });
    let params={
      page: 1,
      pagesize: 10000,
      strcustomercode: '',
      strcustomername: '',
    }
    Customer.getcustomerlist(params).then(data => {
        this.setState({
            customerdata:data.data,
        });
    });
    params={
      page: 1,
      pagesize: 100,
      tablename: 'contracts',
    }
    Workflow_state.getcollist(params).then(data => {
      this.setState({
        tablefielddata: data.data,
      });
    });
    //HRP职员表
    params={
      code: "",
      name: "",
      userid: currentUser.id,
    }
     Customer.queryemployee(params).then(data => {
        this.setState({
          employeedata: data,
        });
    });
    params={
      code: "",
      name: "",
      userid: currentUser.id,
    }
     Customer.querypurchaseemployee(params).then(data => {
      this.setState({
        purchaseemployeedata: data,
      });
    });
     //HRP部门表
    params={
      code: "",
      name: "",
      userid: currentUser.id,
    }
    Customer.querydepartment(params).then(data => {
      this.setState({
        departmentdata: data,
      });
    });
    params={
      code: "",
      userid: currentUser.id,
      contractid:this.props.id,
    }
    Customer.queryyusuan(params).then(data => {
      this.setState({
        yusuandata: data,
      });
    });
    params={
      page: 1,
      pagesize: 5,
      code: '预算控制',
      type: '合同页面',
    }

    GlobalSetting.getlist(params).then(data => {
      //let aa=JSON.parse(data.data[0].value)
      this.setState({
        budgetset: data.data[0].value,
      });
    })
    .catch(error => {
    });
    params={
      page: 1,
      pagesize: 5,
      code: '带量采购部门编码',
      type: '合同新建',
    }

    GlobalSetting.getlist(params).then(data => {
      //let aa=JSON.parse(data.data[0].value)
      this.setState({
        volumepurchaseunit: data.data[0].value,
      });
    })
    .catch(error => {
    });
    params={
      page: 1,
      pagesize: 5,
      code: '合同类别是否框架协议',
      type: '合同新建',
    }

    GlobalSetting.getlist(params).then(data => {
      this.setState({
        kuangjiaxieyi: data.data[0].value,
      });
    })
    .catch(error => {
    });
    params={
      page: 1,
      pagesize: 5,
      code: '是否备案合同',
      type: '合同新建',
    }
    GlobalSetting.getlist(params).then(data => {
      this.setState({
        beianhetong: data.data[0].value,
      });
    })
    .catch(error => {
    });
    this.refreshData(this.props.id)
  }
   refreshData(id = 0) {
    this.props.contractStore.initStore(id,this.props.isbulu);
  }
  handleadd = () => {
      this.refreshData(0)
  };
  handleSave = () => {
    let continues = true;
    let budgets =this.state.budgetset.replace('[','').replace(']','').replace('{','').split('}');
    try {
        budgets.forEach((item) => {
          const ids = item.split(',');
          let qid1 = ids[0];
          let qid2= ids.length>1 ? Number(ids[1]):0;
          let qid3= ids.length>2 ? Number(ids[2]):0;
          let qid4= ids.length>3 ? Number(ids[3]):0;
          if(qid1===this.props.contractStore.contractModel.type[this.props.contractStore.contractModel.type.length-1] && (this.props.contractStore.contractModel.departmentid===qid2 || qid2===0)){
            if(qid3===1){
              if(this.props.contractStore.contractModel.budgetcode===""){
                notification.error("预算编号不能为空");
                continues =false;
                throw new Error("抛出异常跳出");
              }
            }else if(qid3===2){
              this.props.contractStore.contractModel.budgetcode="";
            }
            let budgetamount=0;
            this.state.yusuandata.forEach((item) => {
              if(item.code===this.props.contractStore.contractModel.budgetcode){
                budgetamount=item.surplusamount;
              }
            });
            if(qid4===1){
              if(this.props.contractStore.contractModel.amount>budgetamount){
              notification.error("预算金额小于合同金额");
              }
            }else if(qid4===2){
              if(this.props.contractStore.contractModel.amount>budgetamount){
                notification.error("预算金额小于合同金额,保存失败");
                continues =false;
                throw new Error("抛出异常跳出");
              }
            }
          }
        });
      } catch(e) {
        console.log(e)
    };
    if(!continues){
      return false;
    }
    this.props.contractStore.dataSave();
  };
  handleDelete = () => {
    if (this.props.contractStore.contractModel.userid !== currentUser.id) {
      notification.error("不是创建人，不能删除！");
      return;
    }
    if (this.props.contractStore.contractModel.status !== 0) {
      notification.error("不是草稿状态，不能删除！");
      return;
    }
    confirm({
      title: '确定删除合同,删除后不能恢复?',
      icon: <WarningOutlined />,
      content: this.props.contractStore.contractModel.name,
      okText: '确定',
      okType: 'danger',
      cancelText: '取消',
      onOk: () => {
        this.props.contractStore.dataDelete();
        this.refreshData(0);
      },
    });
  };
  handleCheck = () => {
    this.props.contractStore.billCheck(currentUser.id);
  };
  tabsClick = e => {
    this.setState({
      openpage: e.key,
    });
  };
  handlebackpage= () => {
    customHistory.goBack();
  };

  templateSelect(){
    
      if (this.state.openpage==="jbxx") {
         return (<ContractTable contracttypedata={this.state.contracttypedata}
          amounttypedata={this.state.amounttypedata}
          contracttypenewdata={this.state.contracttypenewdata}
          customerdata={this.state.customerdata}
          employeedata={this.state.employeedata}
          purchaseemployeedata={this.state.purchaseemployeedata}
          departmentdata={this.state.departmentdata}
          yusuandata={this.state.yusuandata}
          volumepurchaseunit ={this.state.volumepurchaseunit}
          kuangjiaxieyi = {this.state.kuangjiaxieyi}
          beianhetong = {this.state.beianhetong}
          tablefielddata= {this.state.tablefielddata}/>);
      } else if(this.state.openpage==="htzw"){
        if(this.props.contractStore.contractModel.type.length <1 && this.props.contractStore.contractModel.departmentid===0){
          notification.success("请先选择合同分类和部门.");
          return;
        }
        return (<Template  style={{ width: 600 }}/>);
      } else if(this.state.openpage==="htfj"){
        return (<AttacheTab id={this.props.contractStore.contractModel.id} billtype="contracts"
          isedit={this.props.contractStore.contractModel.isedit} colcontrol={this.props.contractStore.contractModel.colcontrol}
          allow_col={this.props.contractStore.contractModel.allow_col} status={this.props.contractStore.contractModel.status}/>);
          
      }else{
        return (<EditorDemo />);
      }
  };
  render() {
    if (this.state.loading) return null;
    const enablesave=() => {
      if(GlobalFunctions.getDatetoStr(this.props.contractStore.contractModel.start_date) !==GlobalFunctions.getDatetoStr(this.props.contractStore.contractModel.start_dateold)){
          return true;
      }
      if(GlobalFunctions.getDatetoStr(this.props.contractStore.contractModel.end_date) !==GlobalFunctions.getDatetoStr(this.props.contractStore.contractModel.end_dateold)){
        return true;
      }
      if(GlobalFunctions.getDatetoStr(this.props.contractStore.contractModel.warn_date) !==GlobalFunctions.getDatetoStr(this.props.contractStore.contractModel.warn_dateold)){
        return true;
      }
      if(this.props.contractStore.contractModel.warn_message !==this.props.contractStore.contractModel.warn_messageold){
        return true;
      }
      if(this.props.contractStore.contractModel.recordcode !==this.props.contractStore.contractModel.recordcodeold){
        return true;
      }
      return this.props.contractStore.contractModel.isedit;
    }
    return(
      <div>
        <div style={{ marginBottom: 16 }}>
        <Button type="primary" style={{margin:"10px"}} onClick={() => this.handlebackpage()}>
            <i className="fa fa-reply m-r-5" />
            返回
          </Button>
          <Divider type="vertical" />
          <Button type="primary" onClick={() => this.handleadd()}>
            <i className="fa fa-plus m-r-5" />
            新增
          </Button>
          <Divider type="vertical" />
          <Button type="primary" onClick={() => this.handleSave()} disabled={!enablesave()}>
            <i className="fa fa-save m-r-5" />
            保存
          </Button>
          <Divider type="vertical" />
          <Button type="primary" onClick={() => this.handleDelete()} disabled={this.props.contractStore.contractModel.status !== 0}>
            <i className="fa fa-trash m-r-5" />
            删除
          </Button>
          <Divider type="vertical" />
          <Button type="primary" onClick={() => this.handleCheck()} >
            <i className="fa fa-check m-r-5" />
            {this.props.contractStore.contractModel.status===0 ? "提交":"审核"}
          </Button>
        </div>
      <Menu onClick={this.tabsClick} selectedKeys={this.state.openpage} mode="horizontal">
        <Menu.Item key = "jbxx">基本信息</Menu.Item>
        <Menu.Item key = "htzw">合同正文</Menu.Item>
        <Menu.Item key = "htfj">合同附件</Menu.Item>
      </Menu>
        {this.templateSelect()}
      </div>
    );
  };
}
export default inject('contractStore')(observer(Toolbar));